<!--
 * @Author: your name
 * @Date: 2020-11-20 17:15:12
 * @LastEditTime: 2021-02-18 20:35:10
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \go-admin-business\src\components\uploadImg\index.vue
-->
<template>
    <div>
        <div class="position_re row" :class="sizeType" v-if="!multiple">
            <!-- <div v-if="multiple" class="row">
            <img :src="url" style="width:50px;height:50px" v-for="url in ary" :key="url" alt="">
        </div> -->
            <template v-if="cut && fileType == 'image'">
                <div :class="sizeType" @click.stop="editCropper()">
                    <i class="el-icon-error del" @click="handleRemove" v-if="imgUrl && sizeType != 'circleAvatar'"></i>
                    <img v-if="imgUrl" :src="imgUrl" class="avatar" :class="sizeType" />
                    <i v-else class="el-icon-plus "></i>
                </div>
                <el-dialog :title="title" :visible.sync="openImg" width="800px" append-to-body>
                    <el-row>
                        <el-col :xs="24" :md="12" :style="{ height: '350px' }">
                            <vue-cropper ref="cropper" :img="imgUrl" :info="true" :auto-crop="options.autoCrop"
                                :auto-crop-width="options.autoCropWidth" :auto-crop-height="options.autoCropHeight"
                                :fixed-box="options.fixedBox" @realTime="realTime" />
                        </el-col>
                        <el-col :xs="24" :md="12" :style="{ height: '350px' }">
                            <div class="avatar-upload-preview">
                                <img :src="previews.url" :style="previews.img" />
                            </div>
                        </el-col>
                    </el-row>
                    <br />
                    <el-row>
                        <el-col :lg="2" :md="2">
                            <el-upload name="uploadfile" action="#" :http-request="requestUpload" :show-file-list="false"
                                :before-upload="beforeUpload">
                                <el-button size="small">
                                    上传
                                    <i class="el-icon-upload el-icon--right" />
                                </el-button>
                            </el-upload>
                        </el-col>
                        <el-col :lg="{ span: 1, offset: 2 }" :md="2">
                            <el-button icon="el-icon-plus" size="small" @click="changeScale(1)" />
                        </el-col>
                        <el-col :lg="{ span: 1, offset: 1 }" :md="2">
                            <el-button icon="el-icon-minus" size="small" @click="changeScale(-1)" />
                        </el-col>
                        <el-col :lg="{ span: 1, offset: 1 }" :md="2">
                            <el-button icon="el-icon-refresh-left" size="small" @click="rotateLeft()" />
                        </el-col>
                        <el-col :lg="{ span: 1, offset: 1 }" :md="2">
                            <el-button icon="el-icon-refresh-right" size="small" @click="rotateRight()" />
                        </el-col>
                        <el-col :lg="{ span: 2, offset: 6 }" :md="2">
                            <el-button type="primary" size="small" @click="uploadImg()">提 交</el-button>
                        </el-col>
                    </el-row>
                </el-dialog>
            </template>
            <!-- <el-upload class="avatar-uploader"
            v-else ref="upload" style="width:200px" :action="uploadImageAction"
                v-bind:data="qiniuData" :show-file-list="false" :on-success="handlepostingImageSuccess"
                :on-change="beforeAvatarUpload">
                <template v-if="fileType == 'image'">
                    <img v-if="imgUrl" :src="imgUrl" class="avatar" />
                </template>
                <template v-else>
                    <div>{{name}}</div>
                </template>
                <i class="el-icon-plus avatar-uploader-icon" v-if="!imgUrl"></i>
            </el-upload> -->
            <el-upload name="uploadfile" class="avatar-uploader" style="width:200px" ref="upload" :data="qiniuData"
                :action="uploadImageAction" :show-file-list="false" v-else :on-success="handlepostingImageSuccess"
                :before-upload="beforeAvatarUpload">
                <template v-if="fileType == 'image'">
                    <img v-if="imgUrl" :src="imgUrl" :class="sizeType" />
                </template>
                <template v-else>
                    <div>{{name}}</div>
                </template>
                <i class="el-icon-plus avatar-uploader-icon" v-if="!imgUrl"></i>
            </el-upload>
        </div>

        <el-upload list-type="picture-card" :file-list="fileList" v-else ref="upload" :multiple="true"
            :action="uploadImageAction" :headers="headers" :data="qiniuData" :on-remove="remove"
            :on-success="handlepostingImageSuccess" :before-upload="beforeAvatarUpload">

            <i class="el-icon-plus"></i>
        </el-upload>
    </div>

</template>

<script>
import { getToken } from "@/utils/auth.js";
import { VueCropper } from "vue-cropper";
import axios from "axios";

export default {
    name: "Layout",
    data () {
        return {
            //上传
            uploadImageAction: process.env.VUE_APP_BASE_API + '/api/v1/bw/common/uploadImage',
            qiniuData: {
                token: getToken(),
            },
            headers: {
                Authorization: "Bearer " + getToken()
            },
            // 是否显示弹出层
            openImg: false,
            // 弹出层标题
            title: "上传图片",
            options: {
                img: "",
                autoCrop: true, // 是否默认生成截图框
                autoCropWidth: 200, // 默认生成截图框宽度
                autoCropHeight: 200, // 默认生成截图框高度
                fixedBox: true // 固定截图框大小 不允许改变
            },
            previews: {},
            name: null,
            ary: [],
            fileList: [],
        };
    },
    components: {
        VueCropper
    },
    props: {
        imgUrl: {
            default: ""
        },
        cut: {
            default: true
        },
        sizeType: {
            default: "bigAvatar"
        },
        fileType: {
            default: "image"
        },
        multiple: {
            default: false
        }
    },
    async mounted () {
        // this.options.img = this.imgUrl;
        if (this.multiple) {
            let imgUrl = this.imgUrl.split(',');
            let fileList = [];
            imgUrl.forEach((item, i) => {
                fileList.push({
                    name: i,
                    url: item
                })
            })
            this.fileList = fileList
        }
    },
    methods: {
        abort (e) {
            console.log(e)
        },
        // 编辑头像
        editCropper () {
            this.openImg = true;
        },
        // 覆盖默认的上传行为
        requestUpload () { },
        // 向左旋转
        rotateLeft () {
            this.$refs.cropper.rotateLeft();
        },
        changeStatus (file) {
            console.log(file)
        },
        remove (file, fileList) {
            let imgUrl = [];
            console.log(fileList)
            fileList.forEach(item => {
                if (item.response) {
                    imgUrl.push(item.response.data.url)

                } else {
                    imgUrl.push(item.url)
                }
            })
            let url = imgUrl.join(',')
            this.$emit("update:imgUrl", url);
        },
        // 向右旋转
        rotateRight () {
            this.$refs.cropper.rotateRight();
        },
        // 图片缩放
        changeScale (num) {
            num = num || 1;
            this.$refs.cropper.changeScale(num);
        },
        // 上传预处理
        beforeUpload (file) {
            if (file.type.indexOf("image/") === -1) {
                this.msgError(
                    "文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。"
                );
            } else {
                const reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = () => {
                    this.$emit("update:imgUrl", reader.result);
                };
            }
        },
        handlepostingImageSuccess (res, file, fileList) {
            if (res.code === 200) {
                if (this.multiple) {
                    let imgUrl = [];
                    fileList.forEach(item => {
                        imgUrl.push(item.response.data.url)
                    })
                    let url = imgUrl.join(',')
                    this.$emit("update:imgUrl", url);

                } else {
                    let avatar = res.data.url;
                    this.name =  res.data.url
                    this.$emit("update:imgUrl", avatar);
                }

            }
        },
        beforeAvatarUpload (file) {
            // this.qiniuData.key =
            //     new Date().valueOf() + "." + file.name.split(".")[1];
            const isJPG = file.type == "image/jpeg" || file.type == "image/png";
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (this.fileType == 'image') {
                if (!isJPG) {
                    this.$message.error("上传头像图片只能是 JPG 格式!");
                }
                if (!isLt2M) {
                    this.$message.error("上传头像图片大小不能超过 2MB!");
                }
                return isJPG && isLt2M;
            } else {
                return true
            }
            // return false
        },
        // 上传图片
        async uploadImg () {
            // let qiniuData = await getQiniuToken();
            this.$refs.cropper.getCropBlob(data => {
                console.log(data);
                const formData = new FormData();
                formData.append("uploadfile", data);
                formData.append("token", getToken());
                formData.append(
                    "key",
                    new Date().valueOf() + "." + data.type.split("/")[1]
                );
                axios.post(this.uploadImageAction, formData).then(res => {
                    if (res.code === 200) {
                        let avatar = res.data.url;
                        this.openImg = false;
                        this.$emit("update:imgUrl", avatar);

                        this.$refs.cropper.clearCrop();
                    }
                });
            });
        },
        // 实时预览
        realTime (data) {
            this.previews = data;
        },

        //图片删除
        handleRemove (file, fileList) {
            this.$emit("update:imgUrl", "");
        }
    }
};
</script>

<style lang="scss" scoped>
::v-deep .avatar-uploader .el-upload {
    border: none;
}
.multipleImg {
    width: 50px;
    height: 50px;
    background: #ddd;
    margin-right: 10px;
}
.del {
    position: absolute;
    right: 10px;
    top: 10px;
    color: #ddd;
    font-size: 24px;
    cursor: pointer;
    z-index: 999;
}
.app-container {
    padding: 10px;
    background: #f0f1f5;
}
.bigAvatar {
    width: 200px;
    border: 1px dashed #ddd;
    border-radius: 5px;
    height: 200px;
    line-height: 200px;
    text-align: center;
}
.circleAvatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
}
</style>
